package com.example.shardingsphere.interceptor;

import com.example.shardingsphere.common.config.UserContextHolder;
import com.example.shardingsphere.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 登录拦截器 预处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理器
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前端往后端发送请求的时候，会携带JWT，在请求头里面
        //获取请求头
        String token = request.getHeader("user_token");
        log.info("获取token:{}", token);
        log.info("获取路径：{}", request.getRequestURI());
        //令牌进行解析
        Claims claims = JWTUtil.parseJWT(token);
        //判断是否为空，如果为空，解析失败
        if (null == claims) {
            log.error("解析令牌错误");
            response.setStatus(401);
            return false;
        }
        log.info("解析JWT令牌成功，放行！");

        //构建用户信息
        UserContextHolder.UserInfo userInfo = new UserContextHolder.UserInfo();
        userInfo.setUserId((Long) claims.get("userId"));
        userInfo.setRole((String) claims.get("role_code"));
        //添加自定义属性
        userInfo.addAttribute("ip",request.getRemoteAddr());
        //设置到用户上下文
        UserContextHolder.setUser(userInfo);
        return true;
    }
}
